package com.alpha.schema;

import com.alpha.schema.beans.Schema;
import com.alpha.schema.beans.Table;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;

/**
 * Schema 上下文
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Slf4j
@Getter
@SuppressWarnings("unused")
public class SchemaContext {
    private Schema schema;
    private Schema coreSchema;

    private SchemaContext() {
        try {
            Enumeration<URL> resources = SchemaContext.class.getClassLoader().getResources("schemas.xml");
            while (resources.hasMoreElements()) {
                String path = resources.nextElement().getPath();
                if (!path.contains("alpha-common-service")) {
                    this.schema = SchemaParser.parseSchema(path);
                } else {
                    this.coreSchema = SchemaParser.parseSchema(path);
                }
            }
        } catch (IOException e) {
            log.warn("没有找到alpha-common-service::schemas.xml", e);
        }

        if (schema == null) {
            schema = new Schema();
        }
        if (coreSchema == null) {
            coreSchema = new Schema();
        }
    }

    /**
     * 静态内部类单例模式
     */
    private static class SingletonHolder {
        private static final SchemaContext INSTANCE = new SchemaContext();
    }

    public static SchemaContext getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public List<Table> getAllTable() {
        return this.schema.getTables();
    }

    public Table getTable(String tableName) {
        return this.schema.findTable(tableName);
    }
}
